from django.shortcuts import render
from .models import Area
from django.http import JsonResponse
# Create your views here.
from django.core.cache import cache
from django.views import View


class ProvinceAreasView(View):
    def get(self, request):
        # 增加: 判断是否有缓存
        province_list = cache.get('province_list')

        if not province_list:

            try:
                # 查询所以省份信息
                province_model_list = Area.objects.filter(parent__isnull=True)
                province_list = []
                # 遍历所有查询的省份信息 添加到列表里面
                for province in province_model_list:
                    province_list.append({
                        'id': province.id,
                        'name': province.name})
                cache.set('province_list', province_list, 3600)
            except Exception as e:
                # 查询出错返回错误信息
                return JsonResponse({'code': 400,
                                     'errmsg': '获取省份数据出错'})
            # 返回请求数据
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'province_list': province_list})


class SubAreasView(View):
    def get(self, request, pk):
        sub_dict = cache.get('sub_data_' + pk)
        if not sub_dict:
            try:
                province = Area.objects.get(id=pk)
                sub_model_list = Area.objects.filter(parent=pk)

                sub_list = []
                for sub_model in sub_model_list:
                    sub_list.append({
                        'id': sub_model.id,
                        'name': sub_model.name
                    })
                sub_dict = {'id': province.id,
                            'name': province.name,
                            'subs': sub_list}
                cache.set('sub_data_' + pk, sub_dict, 3600)
            except Exception as e:
                return JsonResponse({'code': 400, 'errmsg': '获取市区信息出错'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'sub_data': sub_dict})
